<template>
  <div class="user-container">
    <!-- Search and Action Bar -->
    <div class="action-bar">
      <el-input
        v-model="searchQuery"
        placeholder="Search users..."
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><search /></el-icon>
          </el-button>
        </template>
      </el-input>
      
      <el-button 
        type="primary" 
        @click="showAddDialog"
        style="margin-left: 20px"
      >
        <el-icon><plus /></el-icon>
        Add User
      </el-button>
    </div>

    <!-- User Table -->
    <el-table 
      :data="filteredUsers" 
      stripe
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="username" label="Username" width="180"></el-table-column>
      <el-table-column prop="name" label="Name"></el-table-column>
      <el-table-column prop="email" label="Email" width="220"></el-table-column>
      <el-table-column prop="role" label="Role" width="120" align="center">
        <template #default="{row}">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
            {{ row.role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="Status" width="120" align="center">
        <template #default="{row}">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="Created" width="180"></el-table-column>
      <el-table-column label="Actions" width="200" align="center">
        <template #default="{row}">
          <el-button 
            size="small" 
            @click="showEditDialog(row)"
            icon="edit"
            circle
          ></el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="confirmDelete(row.id)"
            icon="delete"
            circle
          ></el-button>
          <el-button 
            size="small" 
            type="warning" 
            @click="toggleStatus(row)"
            :icon="row.status === 'ACTIVE' ? 'remove' : 'check'"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalUsers"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- Add/Edit User Dialog -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="userFormRef" 
        :model="userForm" 
        :rules="userRules" 
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="Username" prop="username">
          <el-input v-model="userForm.username" placeholder="Enter username"></el-input>
        </el-form-item>
        
        <el-form-item label="Password" prop="password" v-if="isAddMode">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="Enter password"
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item label="Full Name" prop="name">
          <el-input v-model="userForm.name" placeholder="Enter full name"></el-input>
        </el-form-item>
        
        <el-form-item label="Email" prop="email">
          <el-input v-model="userForm.email" placeholder="Enter email"></el-input>
        </el-form-item>
        
        <el-form-item label="Role" prop="role">
          <el-select v-model="userForm.role" placeholder="Select role" style="width: 100%">
            <el-option label="Admin" value="admin"></el-option>
            <el-option label="Operator" value="operator"></el-option>
            <el-option label="User" value="user"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="Status" prop="status" v-if="!isAddMode">
          <el-switch
            v-model="userForm.status"
            active-value="ACTIVE"
            inactive-value="INACTIVE"
            active-text="Active"
            inactive-text="Inactive"
          ></el-switch>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// Data
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
const dialogVisible = ref(false)
const isAddMode = ref(true)
const userFormRef = ref(null)

const userForm = reactive({
  id: '',
  username: '',
  password: '',
  name: '',
  email: '',
  role: 'user',
  status: 'ACTIVE'
})

const userRules = {
  username: [
    { required: true, message: 'Please input username', trigger: 'blur' },
    { min: 3, max: 20, message: 'Length should be 3 to 20', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' },
    { min: 6, max: 20, message: 'Length should be 6 to 20', trigger: 'blur' }
  ],
  name: [
    { required: true, message: 'Please input full name', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input correct email', trigger: ['blur', 'change'] }
  ],
  role: [
    { required: true, message: 'Please select role', trigger: 'change' }
  ]
}

const users = ref([])

// Computed
const dialogTitle = computed(() => {
  return isAddMode.value ? 'Add New User' : 'Edit User'
})

const filteredUsers = computed(() => {
  const query = searchQuery.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(query) ||
    user.name.toLowerCase().includes(query) ||
    user.email.toLowerCase().includes(query)
  )
})

// Methods
const fetchUsers = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/users', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: searchQuery.value
      }
    })
    users.value = res.data.items
    totalUsers.value = res.data.total
  } catch (error) {
    ElMessage.error('Failed to fetch users')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchUsers()
}

const showAddDialog = () => {
  isAddMode.value = true
  resetForm()
  dialogVisible.value = true
}

const showEditDialog = (user) => {
  isAddMode.value = false
  Object.assign(userForm, user)
  dialogVisible.value = true
}

const resetForm = () => {
  userForm.id = ''
  userForm.username = ''
  userForm.password = ''
  userForm.name = ''
  userForm.email = ''
  userForm.role = 'user'
  userForm.status = 'ACTIVE'
}

const submitForm = async () => {
  try {
    await userFormRef.value.validate()
    
    loading.value = true
    if (isAddMode.value) {
      // Create user
      const res = await request.post('/api/users', userForm)
      users.value.unshift(res.data)
      ElMessage.success('User created successfully')
    } else {
      // Update user
      await request.put(`/api/users/${userForm.id}`, userForm)
      const index = users.value.findIndex(u => u.id === userForm.id)
      if (index !== -1) {
        users.value[index] = { ...users.value[index], ...userForm }
      }
      ElMessage.success('User updated successfully')
    }
    
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('Form validation failed', error)
    if (error.response && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    }
  } finally {
    loading.value = false
  }
}

const confirmDelete = (userId) => {
  ElMessageBox.confirm(
    'Are you sure to delete this user? This action cannot be undone.',
    'Warning',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  ).then(async () => {
    await deleteUser(userId)
  }).catch(() => {
    // Cancel
  })
}

const deleteUser = async (userId) => {
  try {
    loading.value = true
    await request.delete(`/api/users/${userId}`)
    users.value = users.value.filter(user => user.id !== userId)
    ElMessage.success('User deleted successfully')
    fetchUsers()
  } catch (error) {
    ElMessage.error('Failed to delete user')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const toggleStatus = async (user) => {
  try {
    loading.value = true
    await request.put(`/api/users/${user.id}/status`)
    const index = users.value.findIndex(u => u.id === user.id)
    if (index !== -1) {
      users.value[index].status = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
    }
    ElMessage.success(`User ${user.status === 'ACTIVE' ? 'deactivated' : 'activated'}`)
    fetchUsers()
  } catch (error) {
    ElMessage.error('Failed to change user status')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// Lifecycle
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>